package top.amot.forceview.anim

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.locks.LockSupport

class Stepper(private val callback: Runnable?) {
    private val lock: Mutex = Mutex()

    @Volatile
    private var paused = 1

    @Volatile
    private var markAsPaused = 1

    @Volatile
    private var markAsDestroyed = 0

    private val thread:StepperThread by lazy{
        StepperThread()
    }


    fun restart() {
        runBlocking {
            lock.withLock {
                if (paused == 1) {
                    paused = 0
                    LockSupport.unpark(thread)
                }
            }
        }
    }

    fun stop() {
        runBlocking {
            lock.withLock {
                paused = 1
            }
        }
    }

    fun destroy() {
        runBlocking {
            lock.withLock {
                paused = 0
                markAsDestroyed = 1
                /*if (paused == 1) {
                lock.notify()
            }*/
            }
        }
    }

    val isStopped: Boolean
        get() = paused == 1
    val isDestroyed: Boolean
        get() = markAsDestroyed == 1

    internal inner class StepperThread : Thread("StepperThread") {
        init {
            start()
        }

        override fun run() {
            while (true) {
                try {
                    if (markAsDestroyed == 1) return
                    if(paused == 0)
                      callback?.run()
                    else
                        LockSupport.park()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }
}